package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.constant.EsConstant;
import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;

import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;

import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;

import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public PageResult search(RequestParams params) {

        try {
            SearchRequest request = new SearchRequest(EsConstant.INDEX);

            SearchSourceBuilder boolQueryBuilder = getBoolQueryBuilder(params, request);
            String soryBy = params.getSoryBy();

            Integer page = params.getPage();
            Integer size = params.getSize();
          //  request.source().query(boolQueryBuilder);
            request.source().from((page - 1) * size)
                    .size(5)
                    .highlighter(
                            new HighlightBuilder()
                                    .field("name")
                                    .field("city")
                                    .requireFieldMatch(false)
                    )
            ;
            //排序
            if ("score".equals(soryBy)) {
                request.source().sort("score", SortOrder.DESC);
            } else if ("price".equals(soryBy)) {
                request.source().sort("price", SortOrder.ASC);
            }
            //距离排序
            String location = params.getLocation();
            if (location!=null&&!location.equals("")){
                request.source().sort(
                        SortBuilders
                                .geoDistanceSort("location", new GeoPoint(location))
                                .order(SortOrder.ASC)
                                .unit(DistanceUnit.KILOMETERS)
                );
            }


            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            long value = response.getHits().getTotalHits().value;
            ArrayList<HotelDoc> list = new ArrayList<>();
            SearchHit[] hits = response.getHits().getHits();
            for (SearchHit hit : hits) {
                String json = hit.getSourceAsString();
                HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
                //获取高亮字段
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if (highlightFields!=null&&highlightFields.size()>0){
                    HighlightField highlightField = highlightFields.get("name");

                    if (highlightField!=null){
                        //获取高亮字段key值,并转化为字符串
                        String name = highlightField.getFragments()[0].toString();
                       hotelDoc.setName(name);
                    }
                }

                list.add(hotelDoc);
            }
            return new PageResult(value, list);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Map<String, List<String>> buildBasicQuery(RequestParams params) {

        try {
            SearchRequest request = new SearchRequest(EsConstant.INDEX);
            getBoolQueryBuilder(params, request);
            //聚合
            //1.品牌聚合
            addByName(request, "brandAgg", "brand", 10);
            //2.星级聚合
            addByName(request, "starNameAgg", "starName", 10);
            //3.城市聚合
            addByName(request, "cityAgg", "city", 10);
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            //3.处理结果
            Map<String, List<String>> resultMap = new HashMap<>();


            List<String> brandList = getListByAggName(response, "brandAgg");
            resultMap.put("brand", brandList);

            List<String> cityList = getListByAggName(response, "cityAgg");
            resultMap.put("city", cityList);

            List<String> starNameList = getListByAggName(response, "starNameAgg");
            resultMap.put("starName", starNameList);

            return resultMap;

        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    /*
    搜索框自动补全
     */
    @Override
    public List<String> getSuggestions(String prefix) {
        try {
            SearchRequest request = new SearchRequest(EsConstant.INDEX);

            request.source().suggest(new SuggestBuilder().addSuggestion(
                    "suggestions",
                    SuggestBuilders.completionSuggestion("suggestion")
                            .prefix(prefix)
                            .skipDuplicates(true)
                            .size(10)
            ));
            //发起请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //解析结果
            Suggest suggest = response.getSuggest();
            //根据补全查询名称,或取补全结果
            CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
            //获取options
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
          List<String> list = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                String test = option.getText().toString();
                list.add(test);
            }
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据聚合名称获取结果【集合】
     * @param response
     * @param aggName
     * @return
     */
    private List<String> getListByAggName(SearchResponse response, String aggName) {
        List<String> list = new ArrayList<>();
        Aggregations aggregations = response.getAggregations();
       Terms brandAgg = aggregations.get(aggName);
        List<? extends Terms.Bucket> brandAggBuckets = brandAgg.getBuckets();
        for (Terms.Bucket bucket : brandAggBuckets) {
            String key = bucket.getKeyAsString();
            list.add(key);
        }
        return list;
    }




    private void addByName(SearchRequest request, String aggName, String starName, Integer size) {
        request.source()
                .size(10)
                .aggregation(
                        AggregationBuilders
                                .terms(aggName)
                                .field(starName)
                                .size(size)
                );
    }


    private SearchSourceBuilder getBoolQueryBuilder(RequestParams params, SearchRequest request) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //关键字搜索
        String key = params.getKey();
        if (key == null || "".equals(key)) {
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        } else {
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", key));}
        //城市条件
        String city = params.getCity();
        if (city != null && !city.equals("")) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("city", city));
        }
        //品牌条件
        String brand = params.getBrand();
        if (brand != null && !brand.equals("")) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand", brand));
        }
        //价格条件
        Long maxPrice = params.getMaxPrice();
        Long minPrice = params.getMinPrice();
        if (maxPrice != null || minPrice != null) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price")
                    .gte(maxPrice)
                    .lte(minPrice)
            );}
        //星级条件
        String starName = params.getStarName();
        if (starName != null && !starName.equals("")) {
            boolQueryBuilder.must(QueryBuilders.termQuery("starName", starName));}
        //算分控制
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(
                boolQueryBuilder,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true),
                                //算分函数
                                ScoreFunctionBuilders.weightFactorFunction(10)
                        )});
       return request.source().query(functionScoreQueryBuilder);

    }

}
